package com.ylz.tedi.myapplication;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.Surface;

public class PlayerVideoThread extends Thread {

    private String message;
    private Context context;
    //定义一个缓冲区句柄（由屏幕合成程序管理）
    private Surface surface;

    public MediaPlayer getmMediaPlayer() {
        if (null==mMediaPlayer){
            return null;
        }
        return mMediaPlayer;
    }

    //定义一个媒体播发对象
    private MediaPlayer mMediaPlayer;
    private SurfaceTexture surfaceTexture;

    public PlayerVideoThread(Context context, String message, SurfaceTexture surfaceTexture) {
        this.message = message;
        this.context = context;
        this.surfaceTexture = surfaceTexture;
    }

    @Override
    public void run() {
        try {
            mMediaPlayer = new MediaPlayer();
            surface = new Surface(surfaceTexture);
            //把res/raw的资源转化为Uri形式访问(android.resource://)
//                Uri uri = Uri.parse("android.resource://com.github.davidji80.videoplayer/"+R.raw.ansen);
            Uri uri = Uri.parse(message);
            //设置播放资源(可以是应用的资源文件／url／sdcard路径)
            mMediaPlayer.setDataSource(context, uri);
            //设置渲染画板
            mMediaPlayer.setSurface(surface);
            //设置播放类型
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //播放完成监听
            mMediaPlayer.setOnCompletionListener(onCompletionListener);
            //预加载监听
            mMediaPlayer.setOnPreparedListener(onPreparedListener);
            //设置是否保持屏幕常亮
            mMediaPlayer.setScreenOnWhilePlaying(true);
            //同步的方式装载流媒体文件
            mMediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 流媒体播放结束时回调类
     */
    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {

        }
    };


    /**
     * 当装载流媒体完毕的时候回调
     */
    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            //开始播放
            mMediaPlayer.start();
        }
    };

    public void stops() {
        surface = null;
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    public void zanting(){
        if(mMediaPlayer.isPlaying()){
            mMediaPlayer.pause();
        }
    }

}
